<template>
  <div class="gzpbtb-container">
    <!-- Tab切换 -->
    <el-tabs v-model="activeTab" class="data-tabs">
      <!-- 待上报Tab -->
      <el-tab-pane label="填报中" name="pending">
        <!-- 工具栏 -->
        <div class="toolbar">
          <div class="search-section">
            <el-date-picker v-model="selectedWeek" type="week" format="yyyy 第 WW 周" value-format="yyyy-MM-dd"
              placeholder="请选择周" class="date-picker-custom week-picker-enhanced" :editable="false" :clearable="true"
              :picker-options="weekPickerOptions" @change="handleWeekChange">
            </el-date-picker>
            <el-button type="primary" @click="searchData">查询</el-button>
          </div>
        </div>

        <!-- 操作按钮行 -->
        <div class="action-bar">
          <el-button type="warning" @click="openAddDialog">新增</el-button>
          <el-button type="success" @click="editSelected">编辑</el-button>
          <el-button type="info" @click="submitSelected">上报</el-button>
          <el-button type="danger" @click="deleteSelected">删除</el-button>
        </div>

        <div class="table-container">
          <el-table ref="pendingTable" :data="filteredPendingData" border stripe style="width: 100%" height="500"
            @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55">
            </el-table-column>
            <!-- <el-table-column prop="reportWeek" label="填报周" width="100">
            </el-table-column>
            <el-table-column prop="contactPhone" label="联系电话" width="120">
            </el-table-column> -->
            <el-table-column prop="subsidiaryCompany" label="分子公司" width="150">
            </el-table-column>
            <el-table-column prop="cityBureau" label="地市局" width="120">
            </el-table-column>
            <el-table-column prop="countyBureau" label="区县局" width="120">
            </el-table-column>
            <el-table-column prop="substationName" label="变电站名称" width="120">
            </el-table-column>
            <el-table-column prop="transformerName" label="变压器名称" width="120">
            </el-table-column>
            <el-table-column prop="transformerGisid" label="变压器GISID" width="120">
            </el-table-column>
            <el-table-column prop="publicPrivateAttribute" label="公专变属性" width="110">
            </el-table-column>
            <el-table-column prop="regionalFeatures" label="地区特征" width="100">
            </el-table-column>
            <el-table-column prop="transformerCapacity" label="变压器容量(kVA)" width="140">
            </el-table-column>
            <el-table-column prop="phaseNumber" label="相数" width="80">
            </el-table-column>
            <el-table-column prop="lineName" label="线路名称" width="120">
            </el-table-column>
            <el-table-column prop="overloadCause" label="引起重过载原因" width="150">
            </el-table-column>
            <el-table-column prop="preventionMeasures" label="防控措施" width="150">
            </el-table-column>
            <el-table-column prop="lastMonthOverload" label="上月是否发生月过载" width="160">
            </el-table-column>
            <el-table-column prop="overloadDays" label="过载天数" width="100">
            </el-table-column>
            <el-table-column prop="remark" label="备注" min-width="150">
            </el-table-column>
          </el-table>
        </div>

        <!-- 分页组件 -->
        <div class="pagination-container">
          <el-pagination @size-change="handlePendingSizeChange" @current-change="handlePendingCurrentChange"
            :current-page="pendingCurrentPage" :page-sizes="[10, 20, 50, 100]" :page-size="pendingPageSize"
            layout="total, sizes, prev, pager, next, jumper" :total="pendingTotal">
          </el-pagination>
        </div>
      </el-tab-pane>

      <!-- 已上报Tab -->
      <el-tab-pane label="已填报" name="submitted">
        <!-- 工具栏 -->
        <div class="toolbar">
          <div class="search-section">
            <el-date-picker v-model="selectedWeek" type="week" format="yyyy 第 WW 周" value-format="yyyy-MM-dd"
              placeholder="请选择周" class="date-picker-custom week-picker-enhanced" :editable="false" :clearable="true"
              :picker-options="weekPickerOptions" @change="handleWeekChange">
            </el-date-picker>
            <el-button type="primary" @click="searchData">查询按钮</el-button>
          </div>
        </div>

        <!-- 操作按钮行 -->
        <div class="action-bar">
          <el-button type="success" @click="editSelected">编辑</el-button>
        </div>
        <div class="table-container">
          <el-table ref="submittedTable" :data="filteredSubmittedData" border stripe style="width: 100%" height="500"
            @selection-change="handleSubmittedSelectionChange">
            <el-table-column type="selection" width="55">
            </el-table-column>
            <el-table-column prop="reportWeek" label="填报周" width="100">
            </el-table-column>
            <el-table-column prop="contactPhone" label="联系电话" width="120">
            </el-table-column>
            <el-table-column prop="subsidiaryCompany" label="分子公司" width="150">
            </el-table-column>
            <el-table-column prop="cityBureau" label="地市局" width="120">
            </el-table-column>
            <el-table-column prop="countyBureau" label="区县局" width="120">
            </el-table-column>
            <el-table-column prop="substationName" label="变电站名称" width="120">
            </el-table-column>
            <el-table-column prop="transformerName" label="变压器名称" width="120">
            </el-table-column>
            <el-table-column prop="transformerGisid" label="变压器GISID" width="120">
            </el-table-column>
            <el-table-column prop="publicPrivateAttribute" label="公专变属性" width="110">
            </el-table-column>
            <el-table-column prop="regionalFeatures" label="地区特征" width="100">
            </el-table-column>
            <el-table-column prop="transformerCapacity" label="变压器容量(kVA)" width="140">
            </el-table-column>
            <el-table-column prop="phaseNumber" label="相数" width="80">
            </el-table-column>
            <el-table-column prop="lineName" label="线路名称" width="120">
            </el-table-column>
            <el-table-column prop="overloadCause" label="引起重过载原因" width="150">
            </el-table-column>
            <el-table-column prop="preventionMeasures" label="防控措施" width="150">
            </el-table-column>
            <el-table-column prop="lastMonthOverload" label="上月是否发生月过载" width="160">
            </el-table-column>
            <el-table-column prop="overloadDays" label="过载天数" width="100">
            </el-table-column>
<!--            <el-table-column prop="submitTime" label="提交时间" width="180">-->
<!--            </el-table-column>-->
            <el-table-column prop="remark" label="备注" min-width="150">
            </el-table-column>
          </el-table>
        </div>

        <!-- 分页组件 -->
        <div class="pagination-container">
          <el-pagination @size-change="handleSubmittedSizeChange" @current-change="handleSubmittedCurrentChange"
            :current-page="submittedCurrentPage" :page-sizes="[10, 20, 50, 100]" :page-size="submittedPageSize"
            layout="total, sizes, prev, pager, next, jumper" :total="submittedTotal">
          </el-pagination>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="800px" @close="resetForm">
      <el-form ref="dataForm" :model="formData" :rules="formRules" label-width="140px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="填报周" prop="reportWeek">
              <el-date-picker v-model="formData.reportWeek" type="week" format="yyyy 第 WW 周" value-format="yyyy-MM-dd"
                placeholder="请选择填报周" class="date-picker-custom week-picker-enhanced" :editable="false" :clearable="true"
                :picker-options="weekPickerOptions" style="width: 100%">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="联系电话" prop="contactPhone">
              <el-input v-model="formData.contactPhone" placeholder="请输入联系电话"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分子公司" prop="subsidiaryCompany">
              <el-input v-model="formData.subsidiaryCompany" placeholder="请输入分子公司"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="地市局" prop="cityBureau">
              <el-input v-model="formData.cityBureau" placeholder="请输入地市局"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="区县局" prop="countyBureau">
              <el-input v-model="formData.countyBureau" placeholder="请输入区县局"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="变电站名称" prop="substationName">
              <el-input v-model="formData.substationName" placeholder="请输入变电站名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="变压器名称" prop="transformerName">
              <el-input v-model="formData.transformerName" placeholder="请输入变压器名称"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="变压器GISID" prop="transformerGisid">
              <el-input v-model="formData.transformerGisid" placeholder="请输入变压器GISID"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="公专变属性" prop="publicPrivateAttribute">
              <el-input v-model="formData.publicPrivateAttribute" placeholder="请输入公专变属性"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="地区特征" prop="regionalFeatures">
              <el-input v-model="formData.regionalFeatures" placeholder="请输入地区特征"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="变压器容量(kVA)" prop="transformerCapacity">
              <el-input-number v-model="formData.transformerCapacity" :min="0" :step="10" placeholder="请输入变压器容量"
                style="width: 100%">
              </el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="相数" prop="phaseNumber">
              <el-input v-model="formData.phaseNumber" placeholder="请输入相数"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="线路名称" prop="lineName">
              <el-input v-model="formData.lineName" placeholder="请输入线路名称"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="上月是否发生月过载" prop="lastMonthOverload">
              <el-input v-model="formData.lastMonthOverload" placeholder="请输入是否发生月过载"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="过载天数" prop="overloadDays">
              <el-input-number v-model="formData.overloadDays" :min="0" placeholder="请输入过载天数"
                style="width: 100%">
              </el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="引起重过载原因" prop="overloadCause">
              <el-input v-model="formData.overloadCause" type="textarea" :rows="2" placeholder="请输入引起重过载的原因">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="防控措施" prop="preventionMeasures">
              <el-input v-model="formData.preventionMeasures" type="textarea" :rows="2" placeholder="请输入防控措施">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="formData.remark" type="textarea" :rows="2" placeholder="请输入备注信息">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveData">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'GzpbtbIndex',
  data() {
    return {
      activeTab: 'pending',
      dialogVisible: false,
      isEdit: false,
      editIndex: -1,
      editType: 'pending',
      searchKeyword: '',
      selectedRows: [],
      selectedSubmittedRows: [],
      selectedWeek: '',
      weekPickerOptions: {
        firstDayOfWeek: 1, // 周一作为一周的第一天
        disabledDate(time) {
          // 可以在这里设置禁用日期，比如只允许选择未来一个月内的周
          // return time.getTime() > Date.now() + 30 * 24 * 3600 * 1000
          return false // 不禁用任何日期
        },
        shortcuts: [
          {
            text: '本周',
            onClick(picker) {
              const now = new Date()
              const day = now.getDay()
              const diff = now.getDate() - day + (day === 0 ? -6 : 1) // 计算周一的日期
              const monday = new Date(now.setDate(diff))
              picker.$emit('pick', monday)
            }
          },
          {
            text: '上周',
            onClick(picker) {
              const now = new Date()
              const day = now.getDay()
              const diff = now.getDate() - day + (day === 0 ? -6 : 1) - 7 // 上周一
              const lastMonday = new Date(now.setDate(diff))
              picker.$emit('pick', lastMonday)
            }
          },
          {
            text: '下周',
            onClick(picker) {
              const now = new Date()
              const day = now.getDay()
              const diff = now.getDate() - day + (day === 0 ? -6 : 1) + 7 // 下周一
              const nextMonday = new Date(now.setDate(diff))
              picker.$emit('pick', nextMonday)
            }
          }
        ]
      },
      // 分页相关数据
      pendingPageSize: 10,
      pendingCurrentPage: 1,
      submittedPageSize: 10,
      submittedCurrentPage: 1,
      formData: {
        reportWeek: '',
        contactPhone: '',
        subsidiaryCompany: '',
        cityBureau: '',
        countyBureau: '',
        substationName: '',
        transformerName: '',
        transformerGisid: '',
        publicPrivateAttribute: '',
        regionalFeatures: '',
        transformerCapacity: 0,
        phaseNumber: '',
        lineName: '',
        overloadCause: '',
        preventionMeasures: '',
        lastMonthOverload: '',
        overloadDays: 0,
        remark: ''
      },
      formRules: {
        reportWeek: [
          { required: true, message: '请输入填报周', trigger: 'blur' }
        ],

        contactPhone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' }
        ],
        subsidiaryCompany: [
          { required: true, message: '请输入分子公司', trigger: 'blur' }
        ],
        cityBureau: [
          { required: true, message: '请输入地市局', trigger: 'blur' }
        ],
        countyBureau: [
          { required: true, message: '请输入区县局', trigger: 'blur' }
        ],
        substationName: [
          { required: true, message: '请输入变电站名称', trigger: 'blur' }
        ],
        transformerName: [
          { required: true, message: '请输入变压器名称', trigger: 'blur' }
        ],
        transformerGisid: [
          { required: true, message: '请输入变压器GISID', trigger: 'blur' }
        ],
        publicPrivateAttribute: [
          { required: true, message: '请选择公专变属性', trigger: 'change' }
        ],
        regionalFeatures: [
          { required: true, message: '请选择地区特征', trigger: 'change' }
        ],
        transformerCapacity: [
          { required: true, message: '请输入变压器容量', trigger: 'blur' }
        ],
        phaseNumber: [
          { required: true, message: '请选择相数', trigger: 'change' }
        ],
        lineName: [
          { required: true, message: '请输入线路名称', trigger: 'blur' }
        ],
        overloadCause: [
          { required: true, message: '请输入引起重过载原因', trigger: 'blur' }
        ],
        preventionMeasures: [
          { required: true, message: '请输入防控措施', trigger: 'blur' }
        ],
        lastMonthOverload: [
          { required: true, message: '请选择上月是否发生月过载', trigger: 'change' }
        ],
        overloadDays: [
          { required: true, message: '请输入过载天数', trigger: 'blur' }
        ]
      },
      // 初始数据（用于示例展示）
      pendingData: [],
      submittedData: [],
      // 分页总数
      pendingTotal: 0,
      submittedTotal: 0
    }
  },
  computed: {
    dialogTitle() {
      return this.isEdit ? '编辑配变信息' : '新增配变信息'
    },
    filteredPendingData() {
      // 现在数据直接从后端分页获取，不需要前端再次分页
      return this.pendingData
    },
    filteredSubmittedData() {
      // 现在数据直接从后端分页获取，不需要前端再次分页
      return this.submittedData
    },
    // 待上报数据总数（从后端获取）
    // pendingTotal 已在 data 中定义
    // 已上报数据总数（从后端获取）
    // submittedTotal 已在 data 中定义
  },
  mounted() {
    // 初始化时加载数据
    this.loadData()
  },
  watch: {
    // 监听 Tab 切换，重新加载数据
    activeTab(newVal) {
      this.loadData()
    }
  },
  methods: {
    // 搜索数据
    searchData() {
      // 搜索时重置到第一页
      this.pendingCurrentPage = 1
      this.submittedCurrentPage = 1
      // 清空选中项
      this.selectedRows = []
      this.selectedSubmittedRows = []

      // 调用接口获取数据
      this.loadData()
    },

    // 加载数据
    loadData() {
      // 构建查询参数
      const params = {
        pageNum: this.activeTab === 'pending' ? this.pendingCurrentPage : this.submittedCurrentPage,
        pageSize: this.activeTab === 'pending' ? this.pendingPageSize : this.submittedPageSize,
        status: this.activeTab === 'pending' ? 0 : 1  // 0: 待上报(PENDING), 1: 已上报(SUBMITTED)
      }

      // 如果有选择周期，转换为数字格式后添加到查询参数
      if (this.selectedWeek) {
        params.reportWeek = this.convertDateToWeekFormat(this.selectedWeek)
      }

      let proxy = {
        url: 'pbcgzGzpbtb/list',
        data: params
      }

      this.$oPost({ proxy }, (d) => {
        if (d.code === 1000) {
          // 确保 data 存在且格式正确
          if (d.data && d.data.list && Array.isArray(d.data.list)) {
            if (this.activeTab === 'pending') {
              this.pendingData = d.data.list
              this.pendingTotal = d.data.total || 0
            } else {
              this.submittedData = d.data.list
              this.submittedTotal = d.data.total || 0
            }
          } else {
            console.error('API 返回数据格式不正确:', d)
            this.$message.error('数据格式异常')
            this.resetDataArrays()
          }
        } else {
          console.error('API 请求失败:', d)
          this.$message.error(d.message || '查询失败')
          this.resetDataArrays()
        }
      }, (error) => {
        console.error('API 请求出错:', error)
        this.$message.error('网络请求失败')
        this.resetDataArrays()
      })
    },

    // 重置数据数组
    resetDataArrays() {
      if (this.activeTab === 'pending') {
        this.pendingData = []
        this.pendingTotal = 0
      } else {
        this.submittedData = []
        this.submittedTotal = 0
      }
    },

    // 周选择变化处理
    handleWeekChange(value) {
      // 自动触发搜索
      this.pendingCurrentPage = 1
      this.submittedCurrentPage = 1
      // 清空选中项
      this.selectedRows = []
      this.selectedSubmittedRows = []
      // 加载数据
      this.loadData()
      if (value) {
        this.$message.success(`已选择周期：${this.formatWeekDisplay(value)}`)
      }
    },

    // 待上报分页 - 每页条数改变
    handlePendingSizeChange(val) {
      this.pendingPageSize = val
      this.pendingCurrentPage = 1
      // 清空选中项
      this.selectedRows = []
      // 重新加载数据
      this.loadData()
    },

    // 待上报分页 - 当前页改变
    handlePendingCurrentChange(val) {
      this.pendingCurrentPage = val
      // 清空选中项
      this.selectedRows = []
      // 重新加载数据
      this.loadData()
    },

    // 已上报分页 - 每页条数改变
    handleSubmittedSizeChange(val) {
      this.submittedPageSize = val
      this.submittedCurrentPage = 1
      // 清空选中项
      this.selectedSubmittedRows = []
      // 重新加载数据
      this.loadData()
    },

    // 已上报分页 - 当前页改变
    handleSubmittedCurrentChange(val) {
      this.submittedCurrentPage = val
      // 清空选中项
      this.selectedSubmittedRows = []
      // 重新加载数据
      this.loadData()
    },

    // 检查待上报分页是否需要调整
    checkPendingPageAfterDelete() {
      const maxPage = Math.ceil(this.pendingTotal / this.pendingPageSize) || 1
      if (this.pendingCurrentPage > maxPage) {
        this.pendingCurrentPage = maxPage
      }
    },

    // 处理待上报表格选择变化
    handleSelectionChange(selection) {
      this.selectedRows = selection
    },

    // 处理已上报表格选择变化
    handleSubmittedSelectionChange(selection) {
      this.selectedSubmittedRows = selection
    },

    // 编辑选中的记录
    editSelected() {
      const selected = this.activeTab === 'pending' ? this.selectedRows : this.selectedSubmittedRows
      if (selected.length === 0) {
        this.$message.warning('请选择你要编辑的行数！')
        return
      }
      if (selected.length > 1) {
        this.$message.warning('请只选择一条记录进行编辑！')
        return
      }
      if (this.activeTab === 'pending') {
        this.editRow(selected[0])
      } else {
        this.editSubmittedRow(selected[0])
      }
    },

    // 删除选中的记录
    deleteSelected() {
      if (this.activeTab !== 'pending') {
        this.$message.warning('只有待上报的记录才能进行删除！')
        return
      }

      if (this.selectedRows.length === 0) {
        this.$message.warning('请选择你要删除的行数！')
        return
      }

      this.$confirm(`确认删除选中的 ${this.selectedRows.length} 条记录？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 提取选中记录的ID数组
        const ids = this.selectedRows.map(row => row.id)

        let proxy = {
          url: 'pbcgzGzpbtb/batchDelete',
          data: ids  // 直接传入ids数组
        }

        this.$oPost({ proxy }, (d) => {
          if (d.code === 1000) {
            this.$message.success('删除成功！')
            this.selectedRows = []
            // 重新加载数据
            this.loadData()
          } else {
            console.error('API 请求失败:', d)
            this.$message.error(d.message || '删除失败')
          }
        }, (error) => {
          console.error('API 请求出错:', error)
          this.$message.error('网络请求失败')
        })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },

    // 提交选中的记录
    submitSelected() {
      if (this.activeTab !== 'pending') {
        this.$message.warning('只有待上报的记录才能进行上报！')
        return
      }

      if (this.selectedRows.length === 0) {
        this.$message.warning('请选择你要上报的行数！')
        return
      }

      this.$confirm(`确认上报选中的 ${this.selectedRows.length} 条记录？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 提取选中记录的ID数组
        const ids = this.selectedRows.map(row => row.id)

        let proxy = {
          url: 'pbcgzGzpbtb/batchUpdateStatus',
          data: ids  // 直接传入ids数组
        }

        this.$oPost({ proxy }, (d) => {
          if (d.code === 1000) {
            this.$message.success('上报成功！')
            this.selectedRows = []
            // 重新加载数据
            this.loadData()
          } else {
            console.error('API 请求失败:', d)
            this.$message.error(d.message || '上报失败')
          }
        }, (error) => {
          console.error('API 请求出错:', error)
          this.$message.error('网络请求失败')
        })
      }).catch(() => {
        this.$message.info('已取消上报')
      })
    },

    // 打开新增对话框
    openAddDialog() {
      this.isEdit = false
      this.dialogVisible = true
      this.resetForm()
    },

    // 编辑行数据
    editRow(row) {
      this.isEdit = true
      this.editType = 'pending'
      this.editIndex = this.pendingData.findIndex(item => item.id === row.id)
      this.formData = { ...row }

      // 将填报周从数字格式转换为日期格式以便周选择器显示
      if (this.formData.reportWeek && this.formData.reportWeek.length === 6) {
        this.formData.reportWeek = this.convertWeekFormatToDate(this.formData.reportWeek)
      }

      this.dialogVisible = true
    },

    // 编辑已提交行数据
    editSubmittedRow(row) {
      this.isEdit = true
      this.editType = 'submitted'
      this.editIndex = this.submittedData.findIndex(item => item.id === row.id)
      this.formData = { ...row }

      // 将填报周从数字格式转换为日期格式以便周选择器显示
      if (this.formData.reportWeek && this.formData.reportWeek.length === 6) {
        this.formData.reportWeek = this.convertWeekFormatToDate(this.formData.reportWeek)
      }

      this.dialogVisible = true
    },

    // 保存数据
    saveData() {
      this.$refs.dataForm.validate((valid) => {
        if (valid) {
          if (this.isEdit) {
            // 编辑模式 - 调用更新接口
            this.updateData()
          } else {
            // 新增模式 - 调用新增接口
            this.addData()
          }
        } else {
          console.log(this.dataForm);

          this.$message.error('请完善必填信息！')
          return false
        }
      })
    },

    // 新增数据
    addData() {
      const requestData = {
        ...this.formData
      }

      // 将填报周转换为数字格式（如：202536）
      if (requestData.reportWeek) {
        requestData.reportWeek = this.convertDateToWeekFormat(requestData.reportWeek)
      }

      let proxy = {
        url: 'pbcgzGzpbtb/add',
        data: requestData
      }

      this.$oPost({ proxy }, (d) => {
        if (d.code === 1000) {
          this.$message.success('新增成功！')
          this.dialogVisible = false
          this.resetForm()
          // 重新加载数据
          this.loadData()
        } else {
          console.error('新增失败:', d)
          this.$message.error(d.message || '新增失败')
        }
      }, (error) => {
        console.error('新增请求出错:', error)
        this.$message.error('网络请求失败')
      })
    },

    // 将日期格式转换为年周格式（如：yyyy-MM-dd → 202536）
    convertDateToWeekFormat(dateStr) {
      if (!dateStr) return ''

      const date = new Date(dateStr)
      const year = date.getFullYear()
      const weekOfYear = this.getWeekOfYear(date)

      // 返回年份 + 周数（两位数）的格式
      return year + String(weekOfYear).padStart(2, '0')
    },

    // 将年周格式转换为日期格式（如：202536 → yyyy-MM-dd）
    convertWeekFormatToDate(weekStr) {
      if (!weekStr || weekStr.length !== 6) return ''

      const year = parseInt(weekStr.substring(0, 4))
      const week = parseInt(weekStr.substring(4, 6))

      // 简单方法：从年初开始，每周等于7天
      // 计算年初的第一个周一
      const jan4 = new Date(year, 0, 4) // ISO周日期系统使用1月4日确定第一周
      const jan4Day = jan4.getDay()
      const firstMonday = new Date(jan4)

      // 找到第一周的周一
      const daysToMonday = jan4Day === 0 ? -6 : 1 - jan4Day
      firstMonday.setDate(4 + daysToMonday)

      // 计算目标周的周一
      const targetMonday = new Date(firstMonday)
      targetMonday.setDate(firstMonday.getDate() + (week - 1) * 7)

      const targetYear = targetMonday.getFullYear()
      const targetMonth = String(targetMonday.getMonth() + 1).padStart(2, '0')
      const targetDay = String(targetMonday.getDate()).padStart(2, '0')

      return `${targetYear}-${targetMonth}-${targetDay}`
    },

    // 更新数据
    updateData() {
      const requestData = {
        ...this.formData
      }

      // 将填报周转换为数字格式（如：202536）
      if (requestData.reportWeek) {
        requestData.reportWeek = this.convertDateToWeekFormat(requestData.reportWeek)
      }

      let proxy = {
        url: 'pbcgzGzpbtb/update',
        data: requestData
      }

      this.$oPost({ proxy }, (d) => {
        if (d.code === 1000) {
          this.$message.success('修改成功！')
          this.dialogVisible = false
          this.resetForm()
          // 重新加载数据
          this.loadData()
        } else {
          console.error('更新失败:', d)
          this.$message.error(d.message || '修改失败')
        }
      }, (error) => {
        console.error('更新请求出错:', error)
        this.$message.error('网络请求失败')
      })
    },

    // 重置表单
    resetForm() {
      this.formData = {
        reportWeek: '',
        contactPhone: '',
        subsidiaryCompany: '',
        cityBureau: '',
        countyBureau: '',
        substationName: '',
        transformerName: '',
        transformerGisid: '',
        publicPrivateAttribute: '',
        regionalFeatures: '',
        transformerCapacity: 0,
        phaseNumber: '',
        lineName: '',
        overloadCause: '',
        preventionMeasures: '',
        lastMonthOverload: '',
        overloadDays: 0,
        remark: ''
      }
      if (this.$refs.dataForm) {
        this.$refs.dataForm.resetFields()
      }
    },

    // 格式化日期时间
    formatDateTime(date) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      const seconds = String(date.getSeconds()).padStart(2, '0')
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    },

    // 格式化周显示
    formatWeekDisplay(dateStr) {
      if (!dateStr) return ''
      const date = new Date(dateStr)
      const year = date.getFullYear()
      const weekOfYear = this.getWeekOfYear(date)
      return `${year}年第${weekOfYear}周`
    },

    // 获取一年中的第几周
    getWeekOfYear(date) {
      const firstDay = new Date(date.getFullYear(), 0, 1)
      const pastDaysOfYear = (date - firstDay) / 86400000
      return Math.ceil((pastDaysOfYear + firstDay.getDay() + 1) / 7)
    }
  }
}
</script>

<style scoped>
.gzpbtb-container {
  background: #f5f5f5;
  min-height: 100vh;
  padding: 0;
}

/* 工具栏样式 */
.toolbar {
  background: #fff;
  padding: 16px 24px;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.search-section {
  display: flex;
  align-items: center;
  gap: 12px;
}

/* 日期选择器样式 */
.date-picker-custom {
  width: 250px;
}

.week-picker-enhanced .el-input__inner {
  border-radius: 4px;
  font-size: 14px;
  border: 1px solid #dcdfe6;
}

.week-picker-enhanced .el-input__inner:focus {
  border-color: #409EFF;
  outline: none;
}

.week-picker-enhanced .el-input__inner:hover {
  border-color: #c0c4cc;
}

/* 操作按钮行样式 */
.action-bar {
  background: #fff;
  padding: 12px 24px;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  gap: 12px;
  align-items: center;
}

.action-bar .el-button {
  border-radius: 4px;
  font-size: 14px;
  padding: 8px 20px;
  min-width: 80px;
}

/* 按钮颜色定制 */
.action-bar .el-button--warning {
  background-color: #ff9500;
  border-color: #ff9500;
}

.action-bar .el-button--success {
  background-color: #67c23a;
  border-color: #67c23a;
}

.action-bar .el-button--danger {
  background-color: #f56c6c;
  border-color: #f56c6c;
}

.action-bar .el-button--info {
  background-color: #909399;
  border-color: #909399;
}

/* Tab样式 */
.data-tabs {
  background: #fff;
  margin: 0;
  border-radius: 0;
  border-bottom: 1px solid #e4e7ed;
}

.data-tabs .el-tabs__header {
  margin: 0;
  background: #fafafa;
  padding: 0 24px;
  border-bottom: 1px solid #e4e7ed;
}

.data-tabs .el-tabs__nav-wrap {
  padding: 0;
}

.data-tabs .el-tabs__item {
  height: 48px;
  line-height: 48px;
  font-size: 14px;
  padding: 0 20px;
  background: #fafafa;
  border-right: 1px solid #e4e7ed;
}

.data-tabs .el-tabs__item.is-active {
  background: #fff;
  border-bottom: 2px solid #409EFF;
}

.data-tabs .el-tabs__content {
  padding: 0;
}

.data-tabs .el-tab-pane {
  background: #f5f5f5;
  min-height: calc(100vh - 48px);
}

/* 表格容器 */
.table-container {
  background: #fff;
  margin: 0;
  padding: 24px 24px 0 24px;
}

/* 分页容器 */
.pagination-container {
  background: #fff;
  padding: 20px 24px 24px 24px;
  border-top: 1px solid #f0f2f5;
  display: flex;
  justify-content: flex-end;
}

.pagination-container .el-pagination {
  padding: 0;
}

.pagination-container .el-pagination .el-pager li {
  background-color: #fff;
  border: 1px solid #dcdfe6;
  color: #606266;
  margin: 0 2px;
  border-radius: 4px;
}

.pagination-container .el-pagination .el-pager li.active {
  background-color: #409EFF;
  border-color: #409EFF;
  color: #fff;
}

.pagination-container .el-pagination .btn-prev,
.pagination-container .el-pagination .btn-next {
  background-color: #fff;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  margin: 0 2px;
}

.pagination-container .el-pagination .btn-prev:hover,
.pagination-container .el-pagination .btn-next:hover {
  color: #409EFF;
}

/* 表格样式优化 */
.el-table {
  border-radius: 0;
  border: 1px solid #ebeef5;
}

.el-table th {
  background-color: #fafafa;
  color: #606266;
  font-weight: 500;
  font-size: 14px;
  height: 48px;
}

.el-table td {
  font-size: 14px;
  height: 48px;
}

.el-table .el-button--mini {
  padding: 4px 8px;
  margin: 0 2px;
  font-size: 12px;
  border-radius: 3px;
}

/* 对话框样式 */
.el-dialog {
  border-radius: 8px;
}

.el-dialog__header {
  background-color: #fafafa;
  border-bottom: 1px solid #e4e7ed;
  padding: 20px 24px;
}

.el-dialog__title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.el-dialog__body {
  padding: 0;
}

.dialog-footer {
  text-align: right;
  padding: 20px 24px;
  background-color: #fafafa;
  border-top: 1px solid #e4e7ed;
}

.dialog-footer .el-button {
  margin-left: 12px;
}

/* 表单样式优化 */
.el-form {
  padding: 24px;
}

.el-form-item {
  margin-bottom: 22px;
}

.el-form-item__label {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
}

.el-input,
.el-input-number {
  width: 100%;
}

.el-input__inner {
  border-radius: 4px;
  font-size: 14px;
}

/* 搜索框样式 */
.el-input--prefix .el-input__inner {
  padding-left: 35px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .toolbar {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }

  .search-section {
    justify-content: center;
  }

  .action-bar {
    justify-content: center;
    flex-wrap: wrap;
    gap: 8px;
  }

  .action-bar .el-button {
    min-width: 70px;
    padding: 6px 12px;
  }

  .data-tabs {
    padding: 0 12px;
  }

  .table-container {
    padding: 16px 16px 0 16px;
  }

  .pagination-container {
    padding: 16px;
    justify-content: center;
  }

  .el-dialog {
    width: 95% !important;
    margin: 0 auto;
  }

  .el-table {
    font-size: 12px;
  }
}

@media (max-width: 576px) {
  .toolbar {
    padding: 12px 16px;
  }

  .action-bar {
    padding: 8px 16px;
  }

  .search-section .el-input {
    width: 200px !important;
  }

  .date-picker-custom {
    width: 200px !important;
  }

  .data-tabs .el-tabs__header {
    padding: 0 16px;
  }

  .table-container {
    padding: 12px 12px 0 12px;
  }

  .pagination-container {
    padding: 12px;
    justify-content: center;
  }

  .pagination-container .el-pagination {
    font-size: 12px;
  }

  .pagination-container .el-pagination .el-pager li,
  .pagination-container .el-pagination .btn-prev,
  .pagination-container .el-pagination .btn-next {
    min-width: 28px;
    height: 28px;
    line-height: 26px;
    margin: 0 1px;
  }

  .el-form {
    padding: 16px;
  }

  .el-row {
    margin: 0 !important;
  }

  .el-col {
    padding: 0 !important;
  }
}
</style>
